package com.startx.core.tools.xml;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.startx.core.system.constants.Constants;

/**
 * xml 解析工具
 * @author Administrator
 *
 */
public class XmlReader {
	
	/**
	 * 获取xml参数
	 * @param body
	 * @return
	 */
	public static Map<String,String> parseXml(String body) {
		try {
			SAXParserFactory factory = SAXParserFactory.newInstance();
			// 通过factory获取SAXParser实例
			SAXParser parser = factory.newSAXParser();
			// 创建对象SAXParserHandler的实例
			ParserHandler handler = new ParserHandler();
			parser.parse(new ByteArrayInputStream(
					body.replaceAll("\\r|\\n|\\t", Constants.EMPTY_STRING).getBytes()), handler);
			
			return handler.getParams();
		} catch (ParserConfigurationException | SAXException | IOException e) {
			return new HashMap<>();
		}
	}
	
	/**
	 * 解析处理器
	 * @author minghu.zhang
	 */
	public static class ParserHandler extends DefaultHandler {
		
		private String qName;
		private Map<String,String> params = new HashMap<>();
		
		public Map<String,String> getParams() {
			return params;
		}
		
		/**
		 * 用来标识解析开始
		 */
		@Override
		public void startDocument() throws SAXException {
			super.startDocument();
		}

		/**
		 * 用来标识解析结束
		 */
		@Override
		public void endDocument() throws SAXException {
			super.endDocument();
		}

		/**
		 * 解析xml元素
		 */
		@Override
		public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
			super.startElement(uri, localName, qName, attributes);
			this.qName = qName;
		}

		@Override
		public void endElement(String uri, String localName, String qName) throws SAXException {
			super.endElement(uri, localName, qName);
		}

		@Override
		public void characters(char[] ch, int start, int length) throws SAXException {
			super.characters(ch, start, length);
			String value = new String(ch, start, length);
			if(!Constants.EMPTY_STRING.equals(value.trim())) {
				params.put(qName, value);
			}
		}
	}

	/**
	 * 解析xml
	 * @param resourceAsStream
	 * @return
	 */
	public static Map<String, String> parseXml(InputStream resourceAsStream) {
		try {
			SAXParserFactory factory = SAXParserFactory.newInstance();
			// 通过factory获取SAXParser实例
			SAXParser parser = factory.newSAXParser();
			// 创建对象SAXParserHandler的实例
			ParserHandler handler = new ParserHandler();
			parser.parse(resourceAsStream, handler);
			
			return handler.getParams();
		} catch (ParserConfigurationException | SAXException | IOException e) {
			return new HashMap<>();
		}
	}
}